package click

class Website {
     
    String name = "";
    String link = "";
    String ad = "";
    Integer dayOfhit = 0;//当天的统计
    Integer total = 0; // 总流量
    Integer dayOfMax = 0; //设置每天最大流量。0为不限
    Integer increase = 0; // 周的增幅，用这个乘以 dayOfMax
    Date last = new Date();

    static hasMany = [tasks: Task,rate: HourRate]
    static belongsTo = Task 
 
    static constraints = {
            name(size:0..250,blank:true )
            link(size:0..250,blank:false ,unique: true )
            ad(size:0..250,blank:true ) 
            dayOfhit();
            total()
            dayOfMax()
            increase(size:0..100)
            last()
    }
   static mapping = {
        tasks sort  : "id"
        rate sort  : "id"
        rate cascade:"all-delete-orphan"

    }

    String toString(){
        "${name}"
    }
    // 测试是否已经超过时间限制
    boolean rateMatch(){

        Calendar   calendar   =   Calendar.getInstance();
        def int hour = calendar.get(Calendar.HOUR_OF_DAY)
        def int minute = calendar.get(Calendar.MINUTE)

        def boolean  pass = true
        if (rate) {
            rate.each{
                if (it.hour == hour && it.rate != 0) { 
                    
                    if ( it.rate <= total) {
                        pass = false
                    }
                    log.info("rateMatch [(60 / it.rate)*total > minute]  = ${(60 / it.rate)*total} / ${minute}")
                    if ((60 / it.rate)*total > minute) {
                        pass = false
                    }
                }
            }
        }
        return pass
    }
    String toColor(){
        int namesum = 0
        if (name) {
            name.each{
                namesum = it.charAt(0)
            }
        }
        def random = new Random(namesum)
        
        return Integer.toHexString(random.nextInt(255)) + Integer.toHexString(random.nextInt(255)) + Integer.toHexString(random.nextInt(255))
    }
}

